package thinker;

import java.util.Random;

import comm.ChessInfo;
import chess.Chess;
import chess.ChessBoard;
import client.Timer;

public class AIThinker {

	public static final long deadline = 9500;

	private byte color;
	private Timer timer;
	private ChessBoard startBoard;

	private Random rand;

	public AIThinker(byte c) {
		color = c;
		Node.myColor = c;
		rand = new Random();
	}

	public ChessInfo nextMove(ChessBoard b) {
		startBoard = b;
		timer = new Timer(deadline);
		timer.start();
		AlphaBetaSearch search = new AlphaBetaSearch(b);
		if (b.chessed < 1)
			return new ChessInfo((byte) 0, (byte) 7, (byte) 7);
		Chess c = search.bestFirstMove();
		if (c == null) {
			return randomMove();
		}
		else {
			return new ChessInfo(search.bestFirstMove());
		}
	}

	private ChessInfo randomMove() {
		int k = rand.nextInt(startBoard.remaining);
		byte[] rs = { 0, 0, 0, 0 };
		for (byte i = 0; i < ChessBoard.ROWS; i++)
			for (byte j = 0; j < ChessBoard.COLS; j++)
				if (startBoard.isNone(i, j)) {
					k--;
					if (k < 0) {
						return new ChessInfo((byte) 0, color, i, j, rs);
					}
				}
		return new ChessInfo((byte) 0, color, (byte) 0, (byte) 0, rs);
	}

}
